package com.yf.yfmovieapp.controller;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yf.yfmovieapp.pojo.DDUser;
import com.yf.yfmovieapp.service.DDUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @Author Yang_Vincent
 * @Date 2020/8/29 23:13
 */
@RestController
@RequestMapping("/api")
public class RegisterController {

    @Autowired
    private DDUserService ddUserService;


    /**
     * 滴滴影视 注册用户
     * @param username 用户名
     * @param password 密码
     * @param superpass 第二次输入密码
     * @return
     */
    @PostMapping("/register")
    public String registerUsers(
            @RequestParam("username")String username,
            @RequestParam("password")String password,
            @RequestParam("superpass")String superpass,
            HttpServletResponse response
    ){

        //判断用户二次密码是否输入正确
        if (!StringUtils.equals(password, superpass)){
            return "104";
        }

        QueryWrapper<DDUser> wrapper = new QueryWrapper<>();

        wrapper.eq("username", username);

        DDUser one = this.ddUserService.getOne(wrapper);

        //判断当前用户是否已经注册过
        if (one!=null){
            return "105";
        }

        DDUser ddUser = new DDUser();

        ddUser.setUid(RandomUtil.randomNumbers(6));
        ddUser.setPic(null);
        ddUser.setName("");
        ddUser.setVip(1);
        ddUser.setMoney(999);
        ddUser.setToken(UUID.randomUUID().toString().replaceAll("-", ""));
        ddUser.setParent1("1");
        ddUser.setParent2("1");
        ddUser.setParent3("1");
        ddUser.setParent1Rate("5.00");
        ddUser.setParent2Rate("3.00");
        ddUser.setParent3Rate("2.00");
        ddUser.setXjCnt("0");
        ddUser.setAds(new ArrayList());

        ddUser.setUsername(username);

        ddUser.setPassword(password);

        this.ddUserService.save(ddUser);

        PrintWriter pw =null;
        response.setHeader("Content-Type","text/html;charset=UTF-8");
        byte[] bytes = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF, (byte) 0xEF, (byte) 0xBB, (byte) 0xBF, (byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
        String s= "200";
        try {
            pw = response.getWriter();
            pw.write(new String(bytes)+s);
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            pw.close();
        }
        return null;
    }
}
